import React, { useState, useEffect } from 'react';
import {
  Container,
  Typography,
  Grid,
  Paper,
  Box,
  Card,
  CardContent,
  LinearProgress,
  Chip,
  Divider,
  Button,
  List,
  ListItem,
  ListItemText,
  ListItemIcon,
  Avatar,
  Tab,
  Tabs,
  CircularProgress,
  IconButton,
  Menu,
  MenuItem,
  Tooltip
} from '@mui/material';
import {
  TrendingUp as TrendingUpIcon,
  EmojiEvents as TrophyIcon,
  LocalActivity as ActivityIcon,
  Nature as NatureIcon,
  CheckCircle as CheckCircleIcon,
  Schedule as ScheduleIcon,
  Share as ShareIcon,
  MoreVert as MoreVertIcon,
  Download as DownloadIcon,
  BarChart as ChartIcon
} from '@mui/icons-material';
import { useNavigate } from 'react-router-dom';
import { useChallenges } from '../contexts/ChallengeContext';
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip as ChartTooltip,
  ResponsiveContainer,
  PieChart,
  Pie,
  Cell
} from 'recharts';
import axios from 'axios';
import { useAuth } from '../contexts/AuthContext';
import { useActivities } from '../contexts/ActivityContext';

function Dashboard() {
  const navigate = useNavigate();
  const { userChallenges, userPoints } = useChallenges();
  const [activeTab, setActiveTab] = useState(0);
  const { user } = useAuth();
  const [loading, setLoading] = useState(true);
  const [stats, setStats] = useState({
    totalPoints: 0,
    completedChallenges: 0,
    activeChallenges: 0,
    carbonSaved: 0,
    rank: 0
  });
  const { activities } = useActivities();
  const [achievements, setAchievements] = useState([]);
  const [menuAnchor, setMenuAnchor] = useState(null);
  const [chartData, setChartData] = useState([]);
  const [activeChallenges, setActiveChallenges] = useState([]);

  // 合并数据获取
  useEffect(() => {
    const fetchAllData = async () => {
      if (!user) return;
      
      try {
        setLoading(true);
        const [statsRes, achievementsRes, challengesRes] = await Promise.all([
          axios.get(`/api/users/${user.id}/stats`),
          axios.get(`/api/users/${user.id}/achievements`),
          axios.get('/api/users/active-challenges')
        ]);

        setStats(statsRes.data);
        setAchievements(achievementsRes.data);
        setActiveChallenges(challengesRes.data);
      } catch (error) {
        console.error('获取数据失败:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchAllData();
  }, [user]);

  // 模拟获取图表数据
  useEffect(() => {
    const fetchData = async () => {
      try {
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 1000));
        
        setChartData([
          { date: '周一', carbon: 65, points: 120 },
          { date: '周二', carbon: 59, points: 80 },
          { date: '周三', carbon: 80, points: 150 },
          { date: '周四', carbon: 55, points: 90 },
          { date: '周五', carbon: 48, points: 100 },
          { date: '周六', carbon: 42, points: 70 },
          { date: '周日', carbon: 35, points: 110 }
        ]);
        setLoading(false);
      } catch (error) {
        console.error('获取数据失败:', error);
        setLoading(false);
      }
    };
    fetchData();
  }, []);

  const getStatsCards = () => [
    {
      title: '总积分',
      value: stats?.totalPoints || 0,
      icon: <TrophyIcon sx={{ fontSize: 40, color: 'primary.main' }} />
    },
    {
      title: '完成挑战',
      value: stats?.completedChallenges || 0,
      icon: <CheckCircleIcon sx={{ fontSize: 40, color: 'success.main' }} />
    },
    {
      title: '进行中',
      value: stats?.activeChallenges || 0,
      icon: <ScheduleIcon sx={{ fontSize: 40, color: 'warning.main' }} />
    }
  ];

  const handleShare = () => {
    // 实现分享功能
    if (navigator.share) {
      navigator.share({
        title: '我的环保成就',
        text: `我已经获得了 ${userPoints} 积分！`,
        url: window.location.href
      });
    }
  };

  const handleDownload = () => {
    // 实现数据导出功能
    const data = {
      points: userPoints,
      challenges: userChallenges,
      achievements,
      activities
    };
    const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = '环保数据报告.json';
    a.click();
    URL.revokeObjectURL(url);
  };

  // 修改渲染图表的函数
  const renderCharts = () => (
    <Grid container spacing={3}>
      <Grid item xs={12} md={8}>
        <Paper sx={{ p: 3, height: '100%' }}>
          <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 2 }}>
            <Typography variant="h6">碳排放趋势</Typography>
          </Box>
          <Box sx={{ width: '100%', height: 300 }}>
            <ResponsiveContainer>
              <LineChart data={chartData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="date" />
                <YAxis />
                <ChartTooltip />
                <Line
                  type="monotone"
                  dataKey="carbon"
                  stroke="#2E7D32"
                  strokeWidth={2}
                />
              </LineChart>
            </ResponsiveContainer>
          </Box>
        </Paper>
      </Grid>
      
      <Grid item xs={12} md={4}>
        <Paper sx={{ p: 3, height: '100%' }}>
          <Typography variant="h6" gutterBottom>
            积分分布
          </Typography>
          <Box sx={{ width: '100%', height: 300 }}>
            <ResponsiveContainer>
              <PieChart>
                <Pie
                  data={[
                    { name: '挑战', value: 60 },
                    { name: '活动', value: 25 },
                    { name: '减排', value: 15 }
                  ]}
                  cx="50%"
                  cy="50%"
                  innerRadius={60}
                  outerRadius={80}
                  fill="#8884d8"
                >
                  <Cell fill="#2E7D32" />
                  <Cell fill="#1976D2" />
                  <Cell fill="#ED6C02" />
                </Pie>
                <ChartTooltip />
              </PieChart>
            </ResponsiveContainer>
          </Box>
        </Paper>
      </Grid>
    </Grid>
  );

  // 渲染活动进度
  const renderActivityProgress = () => (
    <Grid item xs={12} md={6}>
      <Paper sx={{ p: 2 }}>
        <Typography variant="h6" gutterBottom>
          活动进度
        </Typography>
        {loading ? (
          <CircularProgress />
        ) : activities.length > 0 ? (
          <List>
            {activities.map(activity => (
              <ListItem key={activity._id}>
                <ListItemText
                  primary={activity.title}
                  secondary={
                    <Box>
                      <Typography variant="body2" color="text.secondary">
                        进度: {(activity.progress || 0).toFixed(0)}%
                      </Typography>
                      <Typography variant="body2" color="text.secondary">
                        剩余: {activity.remainingDays} 天
                      </Typography>
                    </Box>
                  }
                />
                <Box sx={{ minWidth: 120 }}>
                  <LinearProgress
                    variant="determinate"
                    value={activity.progress || 0}
                    sx={{ height: 8, borderRadius: 4 }}
                  />
                </Box>
              </ListItem>
            ))}
          </List>
        ) : (
          <Box sx={{ textAlign: 'center', py: 2 }}>
            <Typography color="text.secondary">
              暂无参与的活动
            </Typography>
            <Button
              variant="contained"
              sx={{ mt: 2 }}
              onClick={() => navigate('/community')}
            >
              去参与活动
            </Button>
          </Box>
        )}
      </Paper>
    </Grid>
  );

  // 修改标签页内容渲染
  const renderTabContent = () => {
    switch (activeTab) {
      case 0:
        return (
          <Grid container spacing={3}>
            {activeChallenges.map((challenge) => (
              <Grid item xs={12} md={6} key={challenge._id}>
                <Card>
                  <CardContent>
                    <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
                      <Avatar sx={{ bgcolor: 'primary.main', mr: 2 }}>
                        {challenge.icon || '🌱'}
                      </Avatar>
                      <Typography variant="h6">{challenge.title}</Typography>
                    </Box>
                    <Typography color="text.secondary" paragraph>
                      {challenge.description}
                    </Typography>
                    <Box sx={{ mt: 2 }}>
                      <Typography variant="body2" gutterBottom>
                        进度: {challenge.progress}%
                      </Typography>
                      <LinearProgress
                        variant="determinate"
                        value={challenge.progress}
                        sx={{ height: 8, borderRadius: 4 }}
                      />
                    </Box>
                  </CardContent>
                </Card>
              </Grid>
            ))}
          </Grid>
        );
      case 1:
        return (
          <Grid container spacing={3}>
            {achievements.map((achievement) => (
              <Grid item xs={12} md={4} key={achievement.id}>
                <Card>
                  <CardContent>
                    <Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
                      <Avatar sx={{ bgcolor: 'primary.main', mr: 2 }}>
                        {achievement.icon}
                      </Avatar>
                      <Typography variant="h6">{achievement.title}</Typography>
                    </Box>
                    <Typography variant="body2" color="text.secondary" paragraph>
                      {achievement.description}
                    </Typography>
                    <Box sx={{ mt: 2 }}>
                      <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 1 }}>
                        <Typography variant="body2" color="text.secondary">
                          进度
                        </Typography>
                        <Typography variant="body2" color="text.secondary">
                          {achievement.progress}%
                        </Typography>
                      </Box>
                      <LinearProgress
                        variant="determinate"
                        value={achievement.progress}
                        sx={{ height: 6, borderRadius: 3 }}
                      />
                    </Box>
                  </CardContent>
                </Card>
              </Grid>
            ))}
          </Grid>
        );
      case 2:
        return (
          <Paper sx={{ p: 8 }}>
            <List>
              {activities.map((activity, index) => (
                <React.Fragment key={index}>
                  <ListItem>
                    <ListItemIcon>
                      <Avatar sx={{ bgcolor: 'primary.main' }}>
                        {activity.type === '挑战完成' ? <TrophyIcon /> :
                         activity.type === '参与活动' ? <ActivityIcon /> : 
                         <NatureIcon />}
                      </Avatar>
                    </ListItemIcon>
                    <ListItemText
                      primary={activity.title}
                      secondary={`${activity.date} · ${activity.type} · 获得 ${activity.points} 积分`}
                    />
                    <Chip
                      label={`+${activity.points}`}
                      color="primary"
                      size="small"
                    />
                  </ListItem>
                  {index < activities.length - 1 && <Divider />}
                </React.Fragment>
              ))}
            </List>
          </Paper>
        );
      case 3:
        return renderCharts();
      default:
        return null;
    }
  };

  if (loading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', mt: 4 }}>
        <CircularProgress />
      </Box>
    );
  }

  return (
    <Container maxWidth="lg">
      <Box sx={{ py: 4 }}>
        {/* 顶部操作栏 */}
        <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 4 }}>
          <Typography variant="h4">环保数据仪表盘</Typography>
          <Box>
            <Tooltip title="分享">
              <IconButton onClick={handleShare}>
                <ShareIcon />
              </IconButton>
            </Tooltip>
            <Tooltip title="导出数据">
              <IconButton onClick={handleDownload}>
                <DownloadIcon />
              </IconButton>
            </Tooltip>
          </Box>
        </Box>

        {/* 顶部统计卡片 */}
        <Grid container spacing={3} sx={{ mb: 4 }}>
          {getStatsCards().map((stat, index) => (
            <Grid item xs={12} md={4} key={index}>
              <Paper
                elevation={0}
                sx={{
                  p: 3,
                  textAlign: 'center',
                  bgcolor: 'background.default',
                  border: 1,
                  borderColor: 'divider'
                }}
              >
                <Box sx={{ mb: 2 }}>{stat.icon}</Box>
                <Typography variant="h4" gutterBottom fontWeight="bold">
                  {stat.value}
                </Typography>
                <Typography variant="body1" color="text.secondary">
                  {stat.title}
                </Typography>
              </Paper>
            </Grid>
          ))}
          {renderActivityProgress()}
        </Grid>

        {/* 图表区域 */}
        {renderCharts()}

        {/* 标签页 */}
        <Box sx={{ mb: 3, mt: 4 }}>
          <Tabs
            value={activeTab}
            onChange={(e, newValue) => setActiveTab(newValue)}
            centered
          >
            <Tab label="进行中的挑战" />
            <Tab label="成就" />
            <Tab label="活动记录" />
            <Tab label="数据分析" />
          </Tabs>
        </Box>

        {/* 标签页内容 */}
        <Box sx={{ mt: 3 }}>
          {renderTabContent()}
        </Box>

        {/* 菜单 */}
        <Menu
          anchorEl={menuAnchor}
          open={Boolean(menuAnchor)}
          onClose={() => setMenuAnchor(null)}
        >
          <MenuItem onClick={handleShare}>
            <ListItemIcon>
              <ShareIcon fontSize="small" />
            </ListItemIcon>
            分享
          </MenuItem>
          <MenuItem onClick={handleDownload}>
            <ListItemIcon>
              <DownloadIcon fontSize="small" />
            </ListItemIcon>
            导出数据
          </MenuItem>
        </Menu>
      </Box>
    </Container>
  );
}

export default Dashboard; 